define(['jquery' ,'api', 'echarts', 'webSocketModule', 'httpModule', 'mustache', 'moment'], function($, api, echarts, webSocketModule, httpModule, mustache, moment) {
  var that = {};
  var $node;

  var chartSeries = [];
  var date = [];
  var lineList = [];
  var chartFilterList = [];
  var cacheTpl = {};
  var selfGraphId;
  var myChart;

  var chartTypeMap = {
    0: 'line',
    1: 'bar',
    2: 'pie'
  };

  var initSocket = function(ids) {
    webSocketModule.initSocket(ids);
    webSocketModule.onMessage(that.updateChart);
  };

  var closeSocket = function() {
    webSocketModule.closeSocket();
  };

  var updateChart = function(msg) {
    var items = msg.result[0].gitems;
    var flag = false;

    // 临时保存本次msg的时间列表
    var dateList = [];
    var chartSeriesList = [];

    items && items.map(function(data) {

      // 判断是否有数据推送
      if (data.item) {

        // 判断是否插入过时间
        if (!flag) {
          flag = true;
          data.item && data.item.map(function(item) {
            dateList.push(moment(parseInt(item.clock * 1000)).format('YYYY-MM-DD HH:mm:ss'));
          });
        };
      };

      chartSeries && chartSeries.map(function(serie) {

        // id一致同时message内有新数据
        if (data.gitemid === serie.gitemId && data.item && data.item.length) {
          var items = [];
          data.item && data.item.map(function(item) {
            items.push(item.value);
          });
          serie.data = serie.data.concat(items);
        } else {
          serie.data.push(serie.data[serie.data.length - 1]);
        };
      });
    });
    date = date.concat(dateList);
    that.initChart();
  };

  var switchType = function(evt) {
    $node.find('.label').removeClass('label-info').addClass('label-default');
    $(this).removeClass('label-default').addClass('label-info');
    var count = $(this).attr('data-id');
    var endDate;
    var startDate;
    var isAll = false;
    myChart.showLoading();

    if (count === '-1') {
      isAll = true;
    } else {
      endDate = Date.parse(new Date());
      startDate = endDate - (60 * count);
    };


    that.getChartSeries(selfGraphId, startDate, endDate, isAll);
  };

  var groupChange = function(evt) {
    var groupId = $(this).attr('data-group-id');
    var text = $(this).find('a').html();
    $(this).parent().prev().find('.groupText').text(text);
    $node.find('.htrd-c-chart').hide();
    $node.find('.chart-date-filter').hide();
    $node.find('.hostList').remove();
    $node.find('.configList').remove();
    $node.find('.js-panel-default').hide();
    that.getHostList(groupId);
  };

  var hostChange = function(evt) {
    var hostId = $(this).attr('data-host-id');
    var text = $(this).find('a').html();
    $(this).parent().prev().find('.groupText').text(text);
    $('.js-host-name').text(text);
    $node.find('.htrd-c-chart').hide();
    $node.find('.chart-date-filter').hide();
    $node.find('.js-panel-default').hide();
    getHostConfigList(hostId);
  };

  var hostConfigChange = function(evt) {
    var graphId = $(this).attr('data-graph-id');
    var text = $(this).find('a').html();
    $(this).parent().prev().find('.groupText').text(text);
    selfGraphId = graphId;
    $node.find('.js-panel-default').empty();
    that.initTpl($node.find('.js-panel-default'), cacheTpl['chartInfo'], {
      list: chartFilterList
    }, function(ret) {
      $node.find('.label').eq(0).removeClass('label-default').addClass('label-info');
      $node.find('.js-panel-default').show();
      $node.find('.htrd-c-chart').show();
      $node.find('.chart-date-filter').show();
      that.getChartSeries(graphId);
      that.initSocket(graphId);
    });
  };

  var getGroupList = function() {
    httpModule.baseServ({
      url: api.getHostGroupList
    })
    .then(function(ret) {
      that.initTpl($node.find('.chart-group-filter'), cacheTpl['dropdownMenu'], {
        title: '群组',
        type: 'groupList',
        list: ret.result
      });
    });
  };

  // 获取主机列表
  var getHostList = function(groupid) {
    httpModule.baseServ({
      param: {
        groupids: groupid
      },
      url: api.getHostList
    })
    .then(function(ret) {
      // $node.find('.hostList').remove();
      // $node.find('.configList').remove();
      that.initTpl($node.find('.chart-group-filter'), cacheTpl['dropdownMenu'], {
        title: '主机',
        type: 'hostList',
        list: ret.result
      });
    });
  };

  // 获取主机设备列表
  var getHostConfigList = function(hostid) {
    httpModule.baseServ({
      url: api.getChartSeries,
      param: {
        hostids: hostid
      }
    })
    .then(function(ret) {
      $node.find('.configList').remove();
      that.initTpl($node.find('.chart-group-filter'), cacheTpl['dropdownMenu'], {
        title: '图形',
        type: 'configList',
        list: ret.result
      });
    });
  };


  // 实时更新数据
  var getChartDataByType = function(evt) {
  };

  // 获取host列表
  var getGroupListByHost = function() {

  };

  // 获取chart数据
  var getChartSeries = function(graphId, startDate, endDate, isAll) {

    // 如果没传时间 默认设置为5分钟
    if (!startDate && !endDate) {
      var endDate = Date.parse(new Date());
      var startDate = endDate - (60 * 5) * 1000;
    };

    var param = {
      graphids: graphId || ''
    };

    if (!isAll) {
      param.time_from = parseInt(startDate / 1000);
      param.time_till = parseInt(endDate / 1000);
    };

    // 获取数据
    httpModule.baseServ({
      url: api.getChartSeries,
      param: param,
      dataType: 'jsonp'
    })
    .then(function(ret) {
      var items = [];
      var dateList = [];
      var series = [];
      var units = '';
      lineList = [];

      // console.log('ret', ret.ret);

      if (!!ret.result[0]) {
        items = ret.result[0].gitems;
        items && items.map(function(data) {
          dateList = [];

          var model = {
            name: data.name,
            type: "line",
            smooth: true,
            symbol: "none",
            gitemId: data.gitemid,
            sampling: "average",
            data: []
          };

          lineList.push(data.name);
          data.items && data.items.map(function(item) {
            model.data.push(item.value);
            dateList.push(moment(parseInt(item.clock * 1000)).format('YYYY-MM-DD HH:mm:ss'));
          });
          series.push(model);
        });

        date = dateList;
        chartSeries = series;
        units = items[0].units;
        var type = chartTypeMap[ret.result[0].graphtype];
        console.log('ret.result[0]', ret.result[0]);
        $node.find('.chart-title').html([ret.result[0].hosts[0].name, ret.result[0].name].join(' - '));
        $node.find('.chart-subtext').html(['单位', units].join('/'));
        that.initChart(ret.result[0].name, lineList, type);
      };
    });
  };

  var loadTpls = function() {
    $.get('../template/chartInfo.html')
    .then(function(ret) {
      cacheTpl['chartInfo'] = ret;
    });

    $.get('../template/dropdownMenu.html')
    .then(function(ret) {
      cacheTpl['dropdownMenu'] = ret;
    });
  };

  var initTpl = function(node, tpl, data, callback) {
    var $tpl = mustache.render(tpl, data || {});
    node.append($tpl);
    callback && callback($tpl);
  };

  // 初始化时间段
  var initChartFilter = function() {
    $.getJSON('../json/chartFilterList.json')
    .then(function(ret) {
      chartFilterList = ret;
      that.initTpl($node, cacheTpl['chartFilter'], {
        list: chartFilterList
      });
    });
  };

  // 初始化图表
  var initChart = function(title, line, type) {

    if (type) {
      chartSeries && chartSeries.map(function(item) {
        item.type = type;
      });
    };

    // 基于准备好的dom，初始化echarts图表
    myChart = echarts.init($node.find('#chart')[0]);

    myChart.hideLoading();

    var option = {
        color: [
            '#2ec7c9','#b6a2de','#5ab1ef','#ffb980','#d87a80',
            '#8d98b3','#e5cf0d','#97b552','#95706d','#dc69aa',
            '#07a2a4','#9a7fd1','#588dd5','#f5994e','#c05050',
            '#59678c','#c9ab00','#7eb00a','#6f5553','#c14089'
        ],
        tooltip: {
            trigger: 'axis',
            position: function (pt) {
                return [pt[0], '10%'];
            }
        },
        legend: {
          data: line || lineList
        },

        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: date
        },
        yAxis: {
            type: 'value',
            boundaryGap: [0, '100%'],
            axisLabel: {
              formatter: function (value, index) {
                var text;

                if (value >= 1000 * 1000 * 1000 * 1000) {
                  text = (value / 1000 / 1000 / 1000 / 1000) + 'T';
                }

                else if (value >= 1000 * 1000 * 1000) {
                  text = (value / 1000 / 1000/ 1000) + 'G';
                }

                else if (value >= 1000 * 1000) {
                  text = (value / 1000 / 1000) + 'M';
                }

                else if (value >= 1000) {
                  text = (value / 1000) + 'K';
                }

                else {
                  text = value;
                };
                return text;
              }
            }
        },
        grid: {
          x: 60,
          x2: 60
        },
        series: chartSeries
    };

    // 为echarts对象加载数据
    myChart.setOption(option, true);
  };

  // 初始化获取dom
  var parseDOM = function(node) {
    $node = node;
  };

  // 绑定向外暴露的方法
  var bindListener = function() {
    that.getChartSeries = getChartSeries;
    that.initChart = initChart;
    that.initChartFilter = initChartFilter;
    that.getChartDataByType = getChartDataByType;
    that.initTpl = initTpl;
    that.loadTpls = loadTpls;
    that.getHostList = getHostList;
    that.hostChange = hostChange;
    that.getGroupList = getGroupList;
    that.initSocket = initSocket;
    that.updateChart = updateChart;
    that.closeSocket = closeSocket;
  };

  // 初始化时执行的函数
  var initPlugins = function() {
    that.loadTpls();
    that.initChartFilter();
    that.getGroupList();
    $node.delegate('.label-default', 'click', switchType);
    $node.delegate('.groupList li', 'click', groupChange);
    $node.delegate('.hostList li', 'click', hostChange);
    $node.delegate('.configList li', 'click', hostConfigChange);
  };

  var init = function(node) {
    parseDOM(node);
    bindListener();
    initPlugins();
  };

  that.parseDOM = parseDOM;
  that.bindListener = bindListener;
  that.initPlugins = initPlugins;
  that.init = init;
  return that;
});
